const express = require("express");
const router = express.Router();
const departmentHandler = require("../routes_handle/department");
const { CODE, Response } = require("../utils/response");
const { checkPermission } = require("../middleware/permission");

// 获取部门列表
router.get("/department/list", async (req, res, next) => {
  try {
    const { page = 1, pageSize = 10, search } = req.query;
    const departments = await departmentHandler.getDepartmentList({
      page,
      pageSize,
      search,
    });
    res.status(CODE.SUCCESS).json(Response.success(departments));
  } catch (err) {
    next(err);
  }
});

// 获取部门树形结构
router.get("/department/tree", async (req, res, next) => {
  try {
    const tree = await departmentHandler.getDepartmentTree();
    res.status(CODE.SUCCESS).json(Response.success(tree));
  } catch (err) {
    next(err);
  }
});

// 获取单个部门详情
router.get("/department/detail/:id", async (req, res, next) => {
  try {
    const department = await departmentHandler.getDepartmentById(req.params.id);
    res.status(CODE.SUCCESS).json(Response.success(department));
  } catch (err) {
    next(err);
  }
});

// 添加部门
router.post(
  "/department/create",
  checkPermission("department:add"),
  async (req, res, next) => {
    try {
      const result = await departmentHandler.createDepartment(req.body);
      res.status(CODE.SUCCESS).json(Response.success(result, "部门创建成功"));
    } catch (err) {
      next(err);
    }
  }
);

// 更新部门信息
router.post(
  "/department/update/:id",
  checkPermission("department:edit"),
  async (req, res, next) => {
    try {
      await departmentHandler.updateDepartment(req.params.id, req.body);
      res.status(CODE.SUCCESS).json(Response.success(null, "部门更新成功"));
    } catch (err) {
      next(err);
    }
  }
);

// 删除部门
router.post(
  "/department/delete",
  checkPermission("department:delete"),
  async (req, res, next) => {
    try {
      await departmentHandler.deleteDepartment(req.body.FId);
      res.status(CODE.SUCCESS).json(Response.success(null, "部门删除成功"));
    } catch (err) {
      next(err);
    }
  }
);

module.exports = router;
